<template>
  <div class="sidebar">
    <el-menu :default-active="currentRoute" class="sidebar-el-menu" :collapse="isCollapsed" background-color="#fff"
      text-color="#333" active-text-color="#6190e8" router unique-opened>
      <template v-for="item in sidebarRoutes" :key="item.path">
        <el-menu-item :index="item.path" class="title" @click="handleItemClick(item)">
          <el-icon>
            <component :is="item.meta.icon" />
          </el-icon>
          <span slot="title" class="title">{{ item.meta?.title }}</span>
        </el-menu-item>
      </template>
    </el-menu>
  </div>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const isCollapsed = ref(false);
const router = useRouter();
const route = useRoute();

// 获取当前路径
const currentRoute = computed(() => {
  const path = route.path;
  return path === '/' ? 'user-management' : path.replace('/', '');
});

// 获取侧边栏路由项
const sidebarRoutes = computed(() => {
  const homeRoute = router.getRoutes().find(route => route.path === '/');
  return homeRoute?.children || [];
});

// 跳转到目标路由
const handleItemClick = async (item) => {
  await nextTick(); // 确保 DOM 更新完成
  router.push(item.path);
};
</script>

<style scoped>
.sidebar {
  display: block;
  position: absolute;
  left: 0;
  top: 70px;
  bottom: 0;
  overflow-y: scroll;
}

.sidebar::-webkit-scrollbar {
  width: 0;
}

.sidebar-el-menu:not(.el-menu--collapse) {
  width: 200px;
}

.sidebar>ul {
  height: 100%;
}

.title {
  user-select: none;
}

.el-menu-item {
  border-left: #fff solid 6px;
}

.el-menu-item:hover {
  border-left: #6190e8 solid 6px !important;
  background-color: #e2eff9 !important;
  color: #6190e8 !important;
}

.el-menu-item:hover i {
  color: #6190e8;
}

.el-menu-item.is-active {
  border-left: #6190e8 solid 6px !important;
  background-color: #e2eff9 !important;
  color: #6190e8 !important;
}
</style>
